﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Linq;
using CityLife.GameLogic;
using CityLife.Objects;
using CityLife.Controls;
using CityLife.CityService;
using Facebook.Schema;

namespace CityLife
{



    public class ActiveTool
    {
        public CityLife.CityEditor.Tools ToolType;
      //  public CursorType CursorType = CursorType.Single;
        public Type Design = null;
        public ShopInfo info = null;

    }




	public class CityEditor
	{
		public CityEditor()
		{
			// Insert code required on object creation below this point.
            CityCanvas = new CityCanvas();
            ActiveTool = new ActiveTool();

		}

        public bool Dragging = false;
        public TextBlock SaveIndicator;

        public ActiveTool ActiveTool;
        public CityCanvas  CityCanvas;
        public Grid CityGrid;
        public ElementToolBar ElementInformation;
        private int roadCount = 0;
			
			
			public enum Tools
		{
			Residential1,
			Residential2,
			Residential3,
			Commercial1,
			Commercial2,
			Commercial3,
			Industrial1,
			Industrial2,
			Industrial3,
                Destroy,

                Road1,
                Road2,
                Road3,




                HealthCare1,
                HealthCare2,
                HealthCare3,

                Education1,
                Education2,
                Education3,

                Police1,
                Police2,
                Police3,
                Dummy

			
			
		}


            public void HandleCityClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
            {
                HandleCityClick(sender, e, false);
            }



            Zone currentZone = null;


           // private void CityCursor_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
       public void HandleCityClick(object sender, System.Windows.Input.MouseButtonEventArgs e, bool occupied)
        {
            if (Dragging)
            {
               // Dragging = false;
                return;
            }

           // CityElementType cityElementType = CityElementType.PublicProperty;
          //  CityElementSubType cityElementSubType = CityElementSubType.PublicProperty ;
   

            Type design = (this.ActiveTool.Design);



    






              



                  //  cityElementType = this.ActiveTool.ToolType;
          

                    if (design == null)
                        return;
                     
                    if (!MainPage.Heart.Buy(this.ActiveTool))
                           return;




                    Zone zone = new Zone(this.ActiveTool.info.DesignType);


           if(this.ActiveTool.info.DesignType == typeof(Empty))
           {

                      #region Destroy
                    if (occupied && MainPage.BuildOK)
                    {
                     //   int gridColumn = (int)(sender as Canvas).GetValue(Grid.ColumnProperty);
                      //  int gridRow = (int)(sender as Canvas).GetValue(Grid.RowProperty);



                        int gridColumn = (int)(sender as ICityElement).GridColumn;
                        int gridRow = (int)(sender as ICityElement).GridRow;

                        List<ICityElement> elems = (from a in CityCanvas.CityElements
                                                    where a.GridColumn == gridColumn && a.GridRow == gridRow
                                                    select a).ToList();
                        (sender as Canvas).Visibility = Visibility.Collapsed;

                        foreach (ICityElement elem in elems)
                        {
                            if (!MainPage.Heart.Buy(this.ActiveTool))
                                return;


                            this.CursorHandle(sender as Zone, true, true);


                            CircleCheck check = Check(elem);
                            MainPage.Heart.RemoveCityElement(elem);

                            var control = (from d in CityGrid.Children where Grid.GetColumn(d as FrameworkElement) == gridColumn && Grid.GetRow(d as FrameworkElement) == gridRow select d).FirstOrDefault();

                            CityGrid.Children.Remove(control);

                            Empty empty = new Empty();
                            empty.MouseLeftButtonUp += new MouseButtonEventHandler(CityCursor_MouseLeftButtonUp);
                            empty.SetValue(Grid.ColumnProperty, gridColumn);
                            empty.SetValue(Grid.RowProperty, gridRow);
                            string thename = "Empty_" + gridColumn + "_" + gridRow;
                            empty.Name = thename;

                            CityGrid.Children.Add(empty);

                       

                            if (check.TopZone != null)
                                MainPage.Editor.SetRoad(check.TopZone, 1);

                            if (check.BottomZone != null)
                                MainPage.Editor.SetRoad(check.BottomZone, 1);



                            if (check.RightZone != null)
                                MainPage.Editor.SetRoad(check.RightZone, 1);



                            if (check.LeftZone != null)
                                MainPage.Editor.SetRoad(check.LeftZone, 1);

                        

                            

                           
                        }
                        SaveIndicator.Text = "*";
                        MainPage.Heart.SetDirty();
                    }
                
                    #endregion;
               return;
           }




      if (occupied || !MainPage.BuildOK)
                        return;




                    zone.ElementType = this.ActiveTool.info.ElementType;
                    //zone.ElementSubType = cityElementSubType;
                    zone.ElementOrientation = this.ActiveTool.info.ElementOrientation;
                    //zone.ZoneType = this.ActiveTool.info.ElementType;     
                    zone.CursorType = this.ActiveTool.info.CursorType;

                  //  zone.Type = zone.ZoneType.ToString();
                    zone.GridColumn = (int)(sender as Empty).GetValue(Grid.ColumnProperty);
                    zone.GridRow = (int)(sender as Empty).GetValue(Grid.RowProperty);

                  //  var control = (from d in grid.Children where Grid.GetColumn(d as FrameworkElement) == 3 && Grid.GetRow(d as FrameworkElement) == 4 select d).FirstOrDefault();


                    Empty c = (sender as Empty);


                    // Obtain transform information based off root element
                    GeneralTransform gt = c.TransformToVisual(CityCanvas.Canvas);

                    // Find the four corners of the element
                    Point topLeft = gt.Transform(new Point(0, 0));
                    Point topRight = gt.Transform(new Point(c.RenderSize.Width, 0));
                    Point bottomLeft = gt.Transform(new Point(0, c.RenderSize.Height));
                    Point bottomRight = gt.Transform(new Point(c.RenderSize.Width, c.RenderSize.Height));




                    zone.SetValue(Canvas.LeftProperty, topLeft.X);
                    zone.SetValue(Canvas.TopProperty, topLeft.Y);
                    //zone.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(zone_MouseLeftButtonUp);
                    zone.CreateDate = MainPage.Heart.City.CityStatus.CityDate;
                    zone.UpdateDate = MainPage.Heart.City.CityStatus.CityDate;

                    zone.X = topLeft.X;
                    zone.Y = topLeft.Y;



            

                 
        

                    PlaneProjection proj = new PlaneProjection();
                    //proj.RotationX = 40;			
                    //zone.Projection = proj;
                  

                    zone.SetValue(Canvas.ZIndexProperty , (int)c.GetValue(Grid.RowProperty) * (int)c.GetValue(Grid.ColumnProperty));
                   
                  //  zone.SetValue(Canvas.ZIndexProperty,ElementZindex.Road);
                    zone.ElementStage = CityElementStage.Building;

                    zone.init(MainPage.Heart);

                    this.CursorHandle(zone,true,false);


                    zone.MouseEnter += MainPage.Heart.zone_MouseEnter;
                    zone.MouseLeave += MainPage.Heart.zone_MouseLeave;


                    //clear the old empty box
                    string emptyname = "Empty_" + zone.GridColumn.ToString() + "_" + zone.GridRow.ToString();
                    Empty empty1 = (Empty)MainPage.Editor.CityGrid.FindName(emptyname);
                    if (empty1 != null)
                    {
                        MainPage.Editor.CityGrid.Children.Remove(empty1 as UIElement);
                    }

                    for (int i = 0; i < cleaners.Count; i++)
                    {
                        MainPage.Editor.CityGrid.Children.Remove(cleaners[i] as UIElement);
                    }

                    //MainPage.Editor.CityGrid.Children.Add(zone);
                    
           
                    //adds the item to the board
                    CityCanvas.AddCityElement(zone);







                    if (zone.ElementType == CityElementType.Road)
                    {
                        zone.SetValue(Canvas.ZIndexProperty, 1);
                        #region set up a road



                        //check for city connection
                        if (zone.GridColumn == 0 || zone.GridColumn == CityGrid.ColumnDefinitions.Count - 1
                                || zone.GridRow == 0 || zone.GridRow == CityGrid.RowDefinitions.Count - 1)
                        {
                            AddNeighbours window = new AddNeighbours();
                            window.Show();
                            window.Closed += new EventHandler(window_Closed);



                            currentZone = zone;

                        }
                        
                        //    MainPage.Heart.AddCityElement(zone);
                            SetRoad(zone, 0, Direction.None);

                            roadCount++;
                            if (roadCount == 4)
                            {
                                Car car = new Car();
                                car.SetValue(Canvas.TopProperty, (double)zone.Y);
                                car.SetValue(Canvas.LeftProperty, (double)zone.X);
                                car.SetValue(Canvas.ZIndexProperty, ElementZindex.Car);
                                car.CityCanvas = CityCanvas;
                                Guid g = Guid.NewGuid();

                                car.Name = "Car_" + g.ToString();

                                this.CityCanvas.Canvas.Children.Add(car);


                                MainPage.Heart.Cars.Add(car);
                                roadCount = 0;
                            }
                        
                        #endregion
                    }
             
                    MainPage.Heart.AddCityElement(zone);
                    SaveIndicator.Text = "*";
                    MainPage.Heart.SetDirty();
            







        }
       
        
        
        List<Empty> cleaners = new List<Empty>();

        public void ClearCursor()
        {
              foreach (Empty empty in cleaners)
            {
                empty.clearBorder();
            }
              cleaners.Clear();
        }


        public void CursorHandle(Zone zone, bool move, bool remove)
        {
            if (zone.Design == null)
                return;


            if (remove)
            {
                #region remove
                //CursorType
                switch (zone.Design.Info.CursorType)
                {
                    case CursorType.Double:
                        if (zone.ElementOrientation == CityElementOrientation.Horizontal)
                        {



                            Empty empty = new Empty();
                            empty.MouseLeftButtonUp += new MouseButtonEventHandler(CityCursor_MouseLeftButtonUp);
                            empty.SetValue(Grid.ColumnProperty, zone.GridColumn );
                            empty.SetValue(Grid.RowProperty, zone.GridRow-1);

                            string thename = "Empty_" + zone.GridColumn + "_" + (zone.GridRow-1);
                            empty.Name = thename;

                            //check if it doesnt exist

                            CityGrid.Children.Add(empty);
                            empty.init();


                            //Zone above = new Zone(typeof(Empty));
                            //above.GridColumn = zone.GridColumn+1;
                            //above.GridRow = zone.GridRow;
                            //above.ElementType = CityElementType.Empty;
                            //CityGrid.Children.Add(above);
                            //above.init();
                            //(above.Design as Empty).init();
                           
                        }
                        else
                        {
                            Empty empty = new Empty();
                            empty.MouseLeftButtonUp += new MouseButtonEventHandler(CityCursor_MouseLeftButtonUp);
                            empty.SetValue(Grid.ColumnProperty, zone.GridColumn-1);
                            empty.SetValue(Grid.RowProperty, zone.GridRow);
                            string thename = "Empty_" + (zone.GridColumn-1) + "_" + (zone.GridRow);
                            empty.Name = thename;
                            CityGrid.Children.Add(empty);
                            empty.init();


                            //Zone above = new Zone(typeof(Empty));
                            //above.GridColumn = zone.GridColumn;
                            //above.GridRow = zone.GridRow-1;
                            //above.ElementType = CityElementType.Empty;
                            //CityGrid.Children.Add(above);
                            //above.init();
                            //(above.Design as Empty).init();
   
                        }
                        break;
                    case CursorType.DoubleSquare:
                        break;






                }
                #endregion
            }
            else
            {


                #region build
                //CursorType
                switch (zone.Design.Info.CursorType)
                {
                    case CursorType.Double:
                        if (zone.ElementOrientation == CityElementOrientation.Horizontal)
                        {

                            if (move)
                            {
                                zone.Y = zone.Y - 30;
                                zone.SetValue(Canvas.TopProperty, zone.Y);
                            }

                            //add dummy
                            Dummy d = new Dummy();

                            //remove top element
                            //find the control above
                            string thename = "Empty_" + zone.GridColumn.ToString() + "_" + (zone.GridRow - 1).ToString();
                            Empty above = (Empty)CityGrid.FindName(thename);
                            if (above != null)
                            {
                                
                                CityGrid.Children.Remove(above);
                                //above.Children.Add(d);
                            }
                        }
                        else
                        {
                            //apply rotation
                            TransformGroup tg = new TransformGroup();
                            RotateTransform rt = new RotateTransform();
                            tg.Children.Add(rt);
                            rt.Angle = 90;
                            zone.RenderTransform = tg;
                            if (move)
                            {
                                zone.X = zone.X + 30;
                                zone.SetValue(Canvas.LeftProperty, zone.X);
                            }



                            //remove top element
                            //find the control above
                            string thename = "Empty_" + (zone.GridColumn-1).ToString() + "_" + (zone.GridRow).ToString();
                            Empty above = (Empty)CityGrid.FindName(thename);
                            if (above != null)
                            {

                                CityGrid.Children.Remove(above);
                                //above.Children.Add(d);
                            }

                        }
                        break;
                    case CursorType.DoubleSquare:
                        break;






                }
                #endregion
            }

        }



       public void CreateCursor(object sender, MouseEventArgs e)
       {


           foreach (Empty empty in cleaners)
           {
               empty.clearBorder();
           }
           cleaners.Clear();

           Border b = ((System.Windows.RoutedEventArgs)(e)).OriginalSource as Border;
           if (b != null)
           {

               bool ok = true;
               int column  ;
               int row;
               Empty above = null; 

               if(this.ActiveTool.info!=null)
                   switch (this.ActiveTool.info.CursorType)
                   {
                       case CursorType.Single:
                           //paint double cursor
                           #region Single

                           ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Bottom, ok);
                           ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Right, ok);
                           ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Left, ok);
                           ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Top, ok);

                           cleaners.Add(((b.Parent) as Empty));
                         
                           #endregion
                           this.ActiveTool.info.ElementOrientation = CityElementOrientation.Horizontal;
                           break;

                       case CursorType.Double:
                           #region Double 
                           this.ActiveTool.info.ElementOrientation = CityElementOrientation.Horizontal;
                            column = (int)b.Parent.GetValue(Grid.ColumnProperty);
                            row = (int)b.Parent.GetValue(Grid.RowProperty);

                           //find the control above
                           string thename = "Empty_" + column.ToString() + "_" + (row - 1).ToString();
                           above = (Empty)CityGrid.FindName(thename);

                           if (above == null)
                           {
                               ok = false;
                           }

                           bool altPos = false;

                           if (!ok)
                           {
                               //find the control above
                               thename = "Empty_" + (column-1).ToString() + "_" + (row).ToString();
                               above = (Empty)CityGrid.FindName(thename);

                               if (above == null)
                               {
                                   ok = false;
                               }
                               else
                               {
                                   ok = true;
                                   altPos = true;
                               }
                           }

                           if (altPos)
                           {

                               this.ActiveTool.info.ElementOrientation = CityElementOrientation.Vertical;
                               if (above != null)
                               {
                                   above.setBorder(CityLife.Objects.Direction.Bottom, ok);
                                   above.setBorder(CityLife.Objects.Direction.Top, ok);
                                   above.setBorder(CityLife.Objects.Direction.Left, ok);

                                   cleaners.Add(above);

                               }
                               ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Bottom, ok);
                               ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Right, ok);
                               ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Top, ok);
                               cleaners.Add(((b.Parent) as Empty));

                           }
                           else
                           {


                               if (above != null)
                               {
                                   above.setBorder(CityLife.Objects.Direction.Top, ok);
                                   above.setBorder(CityLife.Objects.Direction.Right, ok);
                                   above.setBorder(CityLife.Objects.Direction.Left, ok);

                                   cleaners.Add(above);

                               }
                               ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Bottom, ok);
                               ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Right, ok);
                               ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Left, ok);
                               cleaners.Add(((b.Parent) as Empty));
                           }
                           #endregion
                           break;

                       case CursorType.DoubleSquare:
                           //paint double cursor
                           #region DoubleSquare
                            column = (int)b.Parent.GetValue(Grid.ColumnProperty);
                            row = (int)b.Parent.GetValue(Grid.RowProperty);



                   

                           //find the control above
                            thename = "Empty_" + column.ToString() + "_" + (row - 1).ToString();
                           above = (Empty)CityGrid.FindName(thename);

                           if (above == null)
                           {
                               ok = false;
                           }

                           //find the control above
                           thename = "Empty_" + (column - 1).ToString() + "_" + (row - 1).ToString();
                           Empty left = (Empty)CityGrid.FindName(thename);

                           if (left == null)
                           {
                               ok = false;
                           }

                           //find the control above
                           thename = "Empty_" + (column - 1).ToString() + "_" + (row).ToString();
                           Empty right = (Empty)CityGrid.FindName(thename);
                           if (right == null)
                           {
                               ok = false;
                           }





                           if (right != null)
                           {
                               right.setBorder(CityLife.Objects.Direction.Bottom, ok);

                               right.setBorder(CityLife.Objects.Direction.Left, ok);
                               cleaners.Add(right);

                           }
                              if (left != null)
                           {
                               left.setBorder(CityLife.Objects.Direction.Top, ok);

                               left.setBorder(CityLife.Objects.Direction.Left, ok);
                               cleaners.Add(left);

                           }

                             if (above != null)
                           {
                               above.setBorder(CityLife.Objects.Direction.Top, ok);
                               above.setBorder(CityLife.Objects.Direction.Right, ok);

                               cleaners.Add(above);

                           }

                             ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Bottom, ok);
                             ((b.Parent) as Empty).setBorder(CityLife.Objects.Direction.Right, ok);
                             cleaners.Add(((b.Parent) as Empty));

                           #endregion
                           break;

                       case CursorType.TripleSquare:

                           break;



                   }


               MainPage.BuildOK = ok;


           

               //   "Empty_" + columns.ToString() + "_" + rows.ToString();
           }
       }





       void window_Closed(object sender, EventArgs e)
       {

           if((sender is AddNeighbours))
               if ((sender as AddNeighbours).DialogResult.Value)
               {
                   MainPage.Heart.AddNeigbour((sender as AddNeighbours).SelectedUser);
                   currentZone.ConnectionID = Convert.ToInt64( (sender as AddNeighbours).SelectedUser.uid);

                   //update the city element for the city

                   CityElement c = (from z in MainPage.Heart.City.Elements
                                    where z.GridColumn == currentZone.GridColumn && z.GridRow == currentZone.GridRow
                                    select z).FirstOrDefault();
                   c.ConnectionID = currentZone.ConnectionID;

               }

           Direction neigbourDirection = Direction.None;
         

           if (currentZone.GridColumn == 0)
                                neigbourDirection = Direction.Left;

           if (currentZone.GridRow == 0)
                                neigbourDirection = Direction.Top;

           if (currentZone.GridColumn == CityGrid.ColumnDefinitions.Count - 1)
                                neigbourDirection = Direction.Right;

           if (currentZone.GridRow == CityGrid.RowDefinitions.Count - 1)
                                neigbourDirection = Direction.Bottom;

         //  MainPage.Heart.AddCityElement(currentZone);
          MainPage.Heart.NeigboursZones.Add(currentZone.ConnectionID, SetRoad(currentZone, 0, neigbourDirection));

           currentZone = null;
       }

  

       void CityCursor_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
       {
           HandleCityClick(sender, e);
       }

       public ICityDesign SetRoad(ICityElement element, int level)
       {

           if (element.ConnectionID > 0)
           {
               Direction neigbourDirection = Direction.None;


               if (element.GridColumn == 0)
                   neigbourDirection = Direction.Left;

               if (element.GridRow == 0)
                   neigbourDirection = Direction.Top;

               if (element.GridColumn == CityGrid.ColumnDefinitions.Count - 1)
                   neigbourDirection = Direction.Right;

               if (element.GridRow == CityGrid.RowDefinitions.Count - 1)
                   neigbourDirection = Direction.Bottom;

               return SetRoad(element, level, neigbourDirection);
           }
           else
           {

              return SetRoad(element, level, Direction.None);
           }
       }


       public ICityDesign SetRoad(ICityElement element, int level, Direction neigbourDirection)
       {
           
           TransformGroup tg = new TransformGroup();
           element.ZoneDirections.Clear();
           CircleCheck check = Check(element);
          // ZoneDirections = new List<Direction>();

           if (neigbourDirection == Direction.Top)
               check.Top = true;
           if (neigbourDirection == Direction.Bottom)
               check.Bottom = true;
           if (neigbourDirection == Direction.Left)
               check.Left = true;
           if (neigbourDirection == Direction.Right)
               check.Right = true;



           ICityDesign cube = null;
           int def = 1;
           switch (def)
           {
               case 1:
                   #region intersection
                   element.Children.Clear();
                   if (check.Top && check.Right && check.Bottom && check.Left)
                   {
                        cube = new Road1Intersection();
                       (cube as UserControl).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);


                       element.Children.Add((cube as UserControl));

                      element.ZoneDirections.Add(Direction.Bottom);
                      element.ZoneDirections.Add(Direction.Top);
                      element.ZoneDirections.Add(Direction.Right);
                      element.ZoneDirections.Add(Direction.Left);
                       break;

                   }


                   if (!check.Top && !check.Right && !check.Bottom && !check.Left)
                   {
                        cube = new Road1None();
                       (cube as Road1None).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       element.Children.Add((Road1None)cube);
                       break;

                   }

                   #endregion

                   #region T junctions
                   if (!check.Top && check.Right && check.Bottom && check.Left)
                   {
                       cube = new Road1T();
                       (cube as Road1T).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 270;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1T).RenderTransform = tg;
                       element.Children.Add((cube as Road1T));
                       element.ZoneDirections.Add(Direction.Right);
                       element.ZoneDirections.Add(Direction.Left);
                       element.ZoneDirections.Add(Direction.Bottom);
                       break;
                   }


                   if (check.Top && !check.Right && check.Bottom && check.Left)
                   {
                       cube = new Road1T();
                       (cube as Road1T).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       element.Children.Add((cube as Road1T));
                       element.ZoneDirections.Add(Direction.Top);
                       element.ZoneDirections.Add(Direction.Left);
                       element.ZoneDirections.Add(Direction.Bottom);

                       break;
                   }


                   if (check.Top && check.Right && !check.Bottom && check.Left)
                   {
                       cube = new Road1T();
                       (cube as Road1T).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 90;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1T).RenderTransform = tg;


                       element.Children.Add((cube as Road1T));

                       element.ZoneDirections.Add(Direction.Top);
                       element.ZoneDirections.Add(Direction.Left);
                       element.ZoneDirections.Add(Direction.Right);
                       break;
                   }


                   if (check.Top && check.Right && check.Bottom && !check.Left)
                   {
                       cube = new Road1T();
                       (cube as Road1T).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 180;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1T).RenderTransform = tg;
                       element.Children.Add((cube as Road1T));
                       element.ZoneDirections.Add(Direction.Top);
                       element.ZoneDirections.Add(Direction.Bottom);
                       element.ZoneDirections.Add(Direction.Right);
                       break;
                   }


                   #endregion

                   #region Turns

                   //Turns
                   if ((check.Top && check.Right) && (!check.Left && !check.Bottom))
                   {
                       cube = new Road1L();
                       (cube as Road1L).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 0;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1L).RenderTransform = tg;
                       element.Children.Add((cube as Road1L));
                       element.ZoneDirections.Add(Direction.Top);
                       element.ZoneDirections.Add(Direction.Right);
                       break;
                   }


                   if ((check.Top && check.Left) && (!check.Right && !check.Bottom))
                   {
                       cube = new Road1L();
                       (cube as Road1L).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 270;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1L).RenderTransform = tg;
                       element.Children.Add((cube as Road1L));
                       element.ZoneDirections.Add(Direction.Top);
                       element.ZoneDirections.Add(Direction.Left);
                       break;
                   }

                   if ((check.Bottom && check.Right) && (!check.Left && !check.Top))
                   {
                       cube = new Road1L();
                       (cube as Road1L).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 90;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1L).RenderTransform = tg;
                       element.Children.Add((cube as Road1L));


                       element.ZoneDirections.Add(Direction.Bottom);
                       element.ZoneDirections.Add(Direction.Right);
                       break;
                   }

                   if ((check.Bottom && check.Left) && (!check.Right && !check.Top))
                   {
                       cube = new Road1L();
                       (cube as Road1L).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 180;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1L).RenderTransform = tg;
                       element.Children.Add((cube as Road1L));
                       element.ZoneDirections.Add(Direction.Bottom);
                       element.ZoneDirections.Add(Direction.Left);
                       break;
                   }
                   #endregion



                   //simple roads
                   #region simpleRoads
                   if (check.Left && check.Right)
                   {
                       cube = new Road1I();
                       (cube as Road1I).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 90;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1I).RenderTransform = tg;
                       element.Children.Add((cube as Road1I));
                       element.ZoneDirections.Add(Direction.Right);
                       element.ZoneDirections.Add(Direction.Left);
                     
                       (cube as INeighbour).SetNeighbour();


                       break;
                   }

                   if (check.Top && check.Bottom)
                   {
                       cube = new Road1I();
                       (cube as Road1I).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       element.Children.Add((cube as Road1I));
                       element.ZoneDirections.Add(Direction.Bottom);
                       element.ZoneDirections.Add(Direction.Top);
                       (cube as INeighbour).SetNeighbour();
                       break;
                   }

                   #endregion

                   //end of the road
                   #region end of the road

                   if (check.Top)
                   {
                       cube = new Road1End();
                       (cube as Road1End).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       element.Children.Add((cube as Road1End));

                       element.ZoneDirections.Add(Direction.Top);
                       (cube as INeighbour).SetNeighbour();
                       break;
                   }

                   if (check.Bottom)
                   {
                       cube = new Road1End();
                       (cube as Road1End).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 180;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1End).RenderTransform = tg;
                       element.Children.Add((cube as Road1End));
                       element.ZoneDirections.Add(Direction.Bottom);
                       (cube as INeighbour).SetNeighbour();
                       break;
                   }

                   if (check.Right)
                   {
                       cube = new Road1End();
                       (cube as Road1End).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();

                       tg.Children.Add(rt);
                       rt.Angle = 90;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1End).RenderTransform = tg;
                       element.Children.Add((cube as Road1End));
                       element.ZoneDirections.Add(Direction.Right);
                       (cube as INeighbour).SetNeighbour();
                       break;
                   }

                   if (check.Left)
                   {
                       cube = new Road1End();
                       (cube as Road1End).SetValue(Canvas.ZIndexProperty, ElementZindex.Road);
                       RotateTransform rt = new RotateTransform();
                       tg.Children.Add(rt);
                       rt.Angle = 270;
                       rt.CenterX = 15;
                       rt.CenterY = 15;
                       (cube as Road1End).RenderTransform = tg;
                       element.Children.Add((cube as Road1End));
                       element.ZoneDirections.Add(Direction.Left);
                       (cube as INeighbour).SetNeighbour();
                       break;
                   }

                   #endregion

                   break;
               case 0:


                   break;
           }


           //if (neigbourDirection != Direction.None)
           //{

           //    NeigbourSign sign = new NeigbourSign();

           //    //get the uri
           //    user u = MainPage.Heart.Neigbours[element.ConnectionID];

           //    Image thumbnail = new Image();
           //    Uri uri = new Uri(u.pic_square, UriKind.Absolute);
           //    ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
           //    sign.Thumb.SetValue(Image.SourceProperty, img);
           //    sign.UserName.Text = u.name;
           //  //  (element as Road1I).Sign.Children.Add(sign);
           //    element.Children.Add(sign);
             

           //   // return;


           //}


           //update dependencies
           level++;
           if (level < 2)
           {
               if (check.TopZone != null)
                   MainPage.Editor.SetRoad(check.TopZone, level);

               if (check.BottomZone != null)
                   MainPage.Editor.SetRoad(check.BottomZone, level);

                 

               if (check.RightZone != null)
                   MainPage.Editor.SetRoad(check.RightZone, level);

          

               if (check.LeftZone != null)
                   MainPage.Editor.SetRoad(check.LeftZone, level);

                  
           }

           return cube as ICityDesign;

       }


       public class CircleCheck
       {
           public bool Top;
           public Zone TopZone;
           public bool Bottom;
           public Zone BottomZone;
           public bool Right;
           public Zone RightZone;
           public bool Left;
           public Zone LeftZone;


       }


       public CircleCheck Check(  ICityElement element)
       {
           //decide the way the road is setup
           CircleCheck check = new CircleCheck();
           //get element at top
           List<ICityElement> elems = (from a in MainPage.Heart.CityCanvas.CityElements
                                       where a.GridColumn == element.GridColumn && a.GridRow == element.GridRow - 1
                                       select a).ToList();

           if (elems.Count > 0)
               if (elems[0].ElementType == CityElementType.Road && (elems[0] as Zone).Visibility== Visibility.Visible)
               {
                   check.Top = true;
                   check.TopZone = (elems[0] as Zone);
               }
               else
                   check.Top = false;

           //get element at Bottom
           elems = (from a in MainPage.Heart.CityCanvas.CityElements
                    where a.GridColumn == element.GridColumn && a.GridRow == element.GridRow + 1
                    select a).ToList();

           if (elems.Count > 0)
               if (elems[0].ElementType == CityElementType.Road && (elems[0] as Zone).Visibility == Visibility.Visible)
               {
                   check.Bottom = true;
                   check.BottomZone = (elems[0] as Zone);
               }
               else
                   check.Bottom = false;

           //get element at Left
           elems = (from a in MainPage.Heart.CityCanvas.CityElements
                    where a.GridColumn == element.GridColumn - 1 && a.GridRow == element.GridRow
                    select a).ToList();

           if (elems.Count > 0)
               if (elems[0].ElementType== CityElementType.Road&& (elems[0] as Zone).Visibility == Visibility.Visible)
               {
                   check.Left = true;
                   check.LeftZone = (elems[0] as Zone);
               }
               else
                   check.Left = false;


           //get element at Right
           elems = (from a in MainPage.Heart.CityCanvas.CityElements
                    where a.GridColumn == element.GridColumn + 1 && a.GridRow == element.GridRow
                    select a).ToList();

           if (elems.Count > 0)
               if (elems[0].ElementType == CityElementType.Road && (elems[0] as Zone).Visibility == Visibility.Visible)
               {
                   check.Right = true;
                   check.RightZone = (elems[0] as Zone);
               }

               else
                   check.Right = false;

           return check;
       }

	}




    public class ElementZindex
    {
        public static int Land = 1;

        public static int Road = 2;
        public static int Car = 3;
        public static int Zone = 4;


    }
}